﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace ConsoleClientTcp
{
    internal class Main
    {

       public TcpClient tcpClient =null;
        public  void CreateClient()
        {
            try
            {
                tcpClient = new TcpClient();
                tcpClient.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到服务器，此时已经创建socket，但是还未建立tcp
                tcpClient.Connected = (client, e) => { return EasyTask.CompletedTask; };//成功连接到服务器
                tcpClient.Disconnecting = (client, e) => { return EasyTask.CompletedTask; };//即将从服务器断开连接。此处仅主动断开才有效。
                tcpClient.Disconnected = (client, e) => { return EasyTask.CompletedTask; };//从服务器断开连接，当连接不成功时不会触发。
                tcpClient.Received = (client, e) =>
                {
                    //从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
                    var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);
                    tcpClient.Logger.Info($"客户端接收到信息：{mes}");
                    return EasyTask.CompletedTask;
                };
                //载入配置
                tcpClient.Setup(new TouchSocketConfig()
                    .SetRemoteIPHost($"192.168.153.1:8053")
                    .ConfigureContainer(a =>
                    {
                        a.AddConsoleLogger();//添加一个日志注入
                    }));

                tcpClient.Connect();//调用连接，当连接不成功时，会抛出异常。

                //Result result = tcpClient.TryConnect();//或者可以调用TryConnect
                //if (result.IsSuccess())
                //{

                //}

                tcpClient.Logger.Info("客户端成功连接");
                tcpClient.Send("RRQM");
            }
            catch (Exception ex)
            {

            }
        }

        public void SendMsg(string msg)
        {
            tcpClient?.Send(msg);
        }
    }
}
